import { Command } from "@colyseus/command";
import { GameRoom } from "../Room/GameRoom";
import { Card, Player } from "../Schema/GameState";
import _ from 'lodash'

export class OnJoinCommand extends Command<GameRoom, {
    sessionId: string
}>{
    execute({ sessionId }) {
        this.state.players.set(sessionId, new Player(sessionId))
        if (this.state.players.size === 1) this.state.host = sessionId
        console.log('cur host:', sessionId)
    }
}

export class OnLeaveCommand extends Command<GameRoom, {
    sessionId: string
}>{
    execute({ sessionId }) {
        this.state.players.delete(sessionId)
        if (this.state.host === sessionId)
            this.state.host = _.sample(Array.from(this.state.players.keys()))!
    }
}

//开始游戏
export class StartCommand extends Command<GameRoom> {
    execute() {
        this.state.isGaming = true
        //每人四张
        this.state.players.forEach(player => {
            this.state.cards = _.shuffle(this.state.cards)
            for (let i of _.range(4)) {
                const num = this.state.cards.pop()!
                player.cardsOfPlayer.push(new Card(num >> 1, num % 2))
            }
            console.log(this.state.cards)
        })
    }
}

//获取一张牌
export class GetCardCommand extends Command<GameRoom, {
    sessionId: string
}>{
    execute({ sessionId }) {
        //没牌了不发
        if (this.state.cards.length === 0) {
            this.state.players.get(sessionId)!.curCard = ''
            return
        }
        //洗牌发牌
        this.state.cards = _.shuffle(this.state.cards)
        const num = this.state.cards.pop()!
        this.state.players.get(sessionId)?.cardsOfPlayer.push(new Card(num >> 1, num % 2))

        //保存当前卡片
        this.state.players.get(sessionId)!.curCard = `${num >> 1}${num % 2}`
    }
}


export class EndCommand extends Command<GameRoom>{
    execute() {
        this.state.cards = _.range(24)
        this.state.cur = 0
        this.state.isGaming = false
        //每位玩家状态重置
        this.state.players.forEach(player => {
            player.isOut = false
            while (player.cardsOfPlayer.length) {
                player.cardsOfPlayer.pop()
            }
        })
    }
}

export class ChangeCardStateCommand extends Command<GameRoom, {
    sessionId: string,
    val: number,
    color: number,
}>{
    execute({ sessionId, val, color }) {
        let cnt = 0
        const cards = this.state.players.get(sessionId)?.cardsOfPlayer!
        cards.forEach(card => {
            if (card.val === val && card.color === color) {
                card.isExpose = !card.isExpose
            }
            if (card.isExpose) cnt++
        })
        if (cnt === cards.length) this.state.players.get(sessionId)!.isOut = true
        else this.state.players.get(sessionId)!.isOut = false

        // console.log('now', sessionId, '\'s state is', `${this.state.players.get(sessionId)!.isOut ? 'out' : 'alive'}`)
    }
}